package cn.gogoyc.org.basic.interceptor;

import cn.gogoyc.org.basic.jwt.JwtUtils;
import cn.gogoyc.org.basic.jwt.LoginData;
import cn.gogoyc.org.basic.jwt.RsaUtils;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PublicKey;

/**
 * Mvc拦截器,配合redis或jwt判断放行使用
 *
 * @author Yang
 * @date 2023/2/10 15:58
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取前端指定请求头的数值
        String token = request.getHeader("token");
        //判断查询到的redis对象是否有值
        if (token != null) {
            try {
                //创建公钥
                PublicKey publicKey = RsaUtils.getPublicKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
                //用公钥解密token
                JwtUtils.getInfoFromToken(token, publicKey, LoginData.class);
                return true;
            } catch (ExpiredJwtException e) {
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().println("{\"success\":false,\"msg\":\"timeout\"}");
                return false;
            }
        }

        response.setContentType("application/json;charset=UTF-8");
        //将拼接的json字符串发送给前端
        response.getWriter().println("{\"success\":false,\"msg\":\"noLogin\"}");
        //拦截请求
        return false;
    }
}
